<template>
  <div class="container">
    <div class="markdown-body" v-if="content===''" v-dompurify-html="displayedContent" ref="contentRef"></div>
    <div class="markdown-body" v-else v-dompurify-html="respondContent" ref="contentRef"></div>
    <div v-show="showCursor" class="cursor"></div>
  </div>
</template>

<script>
import {marked} from "marked";
import hljs from "highlight.js";
import "highlight.js/styles/dark.css";

export default {
  props: {
    content: {
      type: String,
      required: true,
    },
    respondContent:{
      type: String,
      required: true,
    },
    showCursor: {
      type: Boolean,
      default: false,
    },
    lastState:{
      type:Boolean,
      default: false
    },
    currentIndex:{
      type:Number,
      default:0
    },
    lengthList:{
      type:Number,
      default:0
    },
    groupCode:{
      type:Number,
      default:0
    },
    receivedChars: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      displayedContent: "",
      printDelay: 0, // 控制打印速度的延迟（毫秒）
      result:""
    };
  },
  mounted() {

  },
  methods: {
    markdownContent(content) {
      const renderer = new marked.Renderer();
      renderer.code = (code, lang) => {
        const highlightedCode =
            lang && hljs.getLanguage(lang)
                ? hljs.highlight(lang, code).value
                : hljs.highlightAuto(code).value;
        return `<pre><code class="hljs ${lang}">${highlightedCode}</code></pre>`;
      };
      marked.setOptions({ renderer });
      return marked(content);
    },
    printCharacter(char) {
      if (char !== undefined){
        this.result += char;
        this.displayedContent = this.markdownContent(this.result);
      }
    },

  },
  watch: {
    receivedChars: {
      deep: true,
      handler(newChars, oldChars) {
        const newChar = newChars[newChars.length - 1];
        setTimeout(() => {
          this.printCharacter(newChar);
        }, this.printDelay);
        if (this.printDelay === 0){
          this.printDelay = 1000;
        }
      },
    },
  },
};
</script>

<style scoped>
.markdown-body {
  background: inherit;
  line-height: 2;
  font-family: "Roboto Mono";
}
.container {
  position: relative;
}
.cursor {
  content: '';
  content: '';
  position: absolute;
  width: 10px;
  height: 16px;
  background: #d5d9da;
  animation: toggle 0.6s infinite;
  opacity: 0;
  transform: translateY(3px);
}
.cursor.show {
  opacity: 1;
}
@keyframes toggle {
  30% {
    opacity: 1;
  }
}
</style>
